<template>
  <div>
    <h1 class="title">图书馆自习室</h1>

    <!-- 模态框 -->
    <div class="modal" v-if="showModal">
      <div class="modal-content">
        <p v-if="error">{{ error }}</p>
        <!-- 显示错误消息 -->
        <p v-else>座位已选中！</p>
        <!-- 显示成功消息 -->
        <button @click="closeModal">关闭</button>
      </div>
    </div>
    <div class="modal" v-if="showCancel">
      <div class="modal-content">
        <p v-if="error">{{ error }}</p>
        <!-- 显示错误消息 -->
        <p v-else>取消预约吗？</p>
        <!-- 显示成功消息 -->
        <button @click="closeModal">关闭</button>
      </div>
    </div>
    <div v-if="step == 1">
      <!-- 时间段选择的模态框 -->
      <div class="time-slot-modal" v-if="showTimeSlotModal">
        <div class="modal-content">
          <h2>选择预约日期</h2>
          <div class="seat-buttons dateitem">
            <button
              v-for="item in dateList"
              :key="item"
              :class="[
                'time-slot-button',
                curselectedDateSlot === item ? 'curChoose' : '',
              ]"
              @click="selectDay(item)"
            >
              {{ dateFilter(item) }}
            </button>
          </div>
          <button @click="step = 2" class="nextbtn">下一步</button>
        </div>
      </div>
    </div>
    <div v-else-if="step == 2" >
      <!-- 时间段选择的模态框 -->
      <div class="time-slot-modal" v-if="showTimeSlotModal">
        <div class="modal-content" style="position: relative">
          <div class="arrow-left-box" >
            <div class="arrow-left" @click="step=1;selectedTimeSlot = ''"></div>
          </div>
          <h2>选择时间段</h2>
          <div class="seat-buttons">
            <button
              v-for="timeSlot in timeSlots"
              :key="timeSlot.id"
              class="time-slot-button"
              :class="{
                'selected-time-slot': selectedTimeSlot === timeSlot.id,
              }"
              @click="selectTimeSlot(timeSlot.id)"
            >
              {{ timeSlot.label }}
            </button>
          </div>
          <div class="btnbox">
            <button @click="cancelTimeSlot">取消</button>
            <button
              :style="{ opacity: selectedTimeSlot == null ? '0.3' : '1' }"
              @click="confirmTimeSlot"
              :disabled="selectedTimeSlot === null"
            >
              确认
            </button>
          </div>
        </div>
      </div>
    </div>
    <div v-else-if="step == 3" >
      <div class="seat-selector"  >
        <div class="arrow-left-box" >
          <div class="arrow-left" @click="step=2;showTimeSlotModal=true"></div>
        </div>

        <button
          v-for="(seat, index) in seatList"
          :key="index"
          class="seat-button"
          :class="{ 'selected-seat': seat[index + 1] }"
          @click="selectSeat(index)"
        >
          座位{{ index + 1 }}
        </button>
      </div>
    </div>
    <div v-else-if="step == 4" >
      <div class="seat-selector"  >
        <div class="arrow-left-box" >
          <div  @click="resetChoose" style="cursor: pointer">选择时间段</div>
        </div>

        <button
            v-for="(seat, index) in seatList2"
            :key="index"
            class="seat-button"
            @click="showMessageFun('请先选择时间段')"
        >
          座位{{ index + 1 }}
        </button>
      </div>
    </div>

    <div class="tips" v-if="showMsg">
      <div class="messagetext">
        {{ message }}
      </div>
    </div>
  </div>
</template>

<script>
import $ from "jquery";
// import { ref } from 'vue';
import { ref, onMounted } from "vue";
import { useStore } from "vuex";
export default {
  name: "RanklistIndexView",
  setup() {
    const store = useStore();
    let seatId = ref();
    let error = ref(""); // 添加一个用于保存错误信息的变量
    let seatIdStatus = ref(); // 新增一个变量来存储座位状态
    let seatStatusList = ref([]); // 存储座位状态的整数列表
    let selectTSlot = ref(""); // 获取的时间段值，用于传给后端
    const seatstatus = () => {
      error.value = ""; // 在请求之前清除之前的错误信息
      const seatIdValue = seatId.value; // 使用10作为基数  //改  //没用
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/seatstatus/",
        type: "post",
        data: {
          seatId: seatIdValue,
          selectedTimeSlot: selectTSlot.value,
        },
        headers: {
          Authorization: "Bearer " + store.state.user.token,
        },
        success(resp) {
          if (resp.error_message === "座位状态更新成功") {
            console.log("座位状态保存成功", resp.data);
          } else {
            // 处理错误
            console.error("座位状态保存失败1", resp.error_message);
            error = resp.error_message; // 将错误信息保存到error变量中
          }
        },
        error(xhr, status, error) {
          console.error("座位状态保存失败2", error);
          error = "座位状态保存失败2"; // 处理请求失败的情况，例如显示错误消息
        },
      });
    };

    //获取座位status列表
    const getSeatId = () => {
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/getseatstatus/",
        type: "post", // 使用 GET 请求
        dataType: "json", // 声明数据类型为 JSON

        success: function (data) {
          seatStatusList.value = data;
        },
        error: function (xhr, status, error) {
          console.error("获取Getseatid失败");
          console.error("发生错误:", error);
        },
      });
    };

    onMounted(() => {
      // getSeatId(); // 在组件挂载后立即调用getSeatId
    });

    //获取当前登录的用户名
    const getCurrentUser = () => {
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/currentUser", // 后端提供的获取当前登录用户信息的接口
        type: "GET",
        headers: {
          Authorization: "Bearer " + store.state.user.token,
        },
        dataType: "json",
        success: function (data) {
          // 在这里处理获取到的用户信息
          console.log("当前登录用户信息：", data.username);
        },
        error: function (xhr, status, error) {
          console.error("获取当前登录用户信息失败", error);
        },
      });
    };

    // 在需要获取当前用户信息的地方调用这个函数
    getCurrentUser();

    return {
      seatStatusList: seatStatusList, // 存储座位状态的整数列表
      seatId,
      seatstatus,
      error, // 将error变量暴露出去以在模板中显示错误信息
      getSeatId,
      seatIdStatus,
      selectTSlot,
    };
  },

  data() {
    return {
      seatList2:[
        {1:false},{2:false},{3:false},{4:false},{5:false},
        {6:false},{7:false},{8:false},{9:false},{10:false},
        {11:false},{12:false},{13:false},{14:false},{15:false},
        {16:false},{17:false},{18:false},{19:false},{20:false},
        {21:false},{22:false},{23:false},{24:false},{25:false},

      ],
      showMsg: false,
      message: "",
      seatList: [],
      curselectedDateSlot: "",
      selectedDateSlot: "",
      step: 1,
      timeSlots: [
        { id: 1, label: "07:00~09:00" },
        { id: 2, label: "09:10~11:10" },
        { id: 3, label: "11:20~13:20" },
        { id: 4, label: "13:30~15:30" },
        { id: 5, label: "15:40~17:40" },
        { id: 6, label: "17:50~19:50" },
        { id: 7, label: "20:00~23:00" },
      ], //设置可以选择的时间段
      selectedTimeSlot: null, //选取的时间段
      seatOptions: [],
      selectedSeat: null,
      showModal: false,
      showCancel: false,
      showTimeSlotModal: true, // 控制时间段选择弹窗的显示状态
    };
  },
  // 日期
  computed: {
    dateList() {
      const currentDate = new Date();
      const today = currentDate.toLocaleDateString();
      const tomorrow = new Date(currentDate);
      tomorrow.setDate(currentDate.getDate() + 1);
      const twoDaysLater = new Date(currentDate);
      twoDaysLater.setDate(currentDate.getDate() + 2);
      return [today, tomorrow, twoDaysLater];
    },
  },
  created() {
    for (let row = 1; row <= 5; row++) {
      for (let col = 1; col <= 5; col++) {
        const seatNumber = (row - 1) * 5 + col;
        const status = this.seatStatusList[seatNumber - 1];
        // console.log("status", status);
        this.seatOptions.push({
          id: seatNumber,
          label: `座位${seatNumber}`,
          status: status,
          selectedTimeSlot: null, // 添加时间段属性
        });
      }
    }
  },
  methods: {
    //提示信息
    showMessageFun(msg = "", time = 3000) {
      let that = this;
      that.message = msg;
      that.showMsg = true;
      setTimeout(function () {
        that.showMsg = false;
      }, time);
    },
    //选择第几天
    selectDay(item) {
      this.curselectedDateSlot = item;
      this.selectedDateSlot = this.dateFilter(item);
      console.log(this.selectedDateSlot);
    },
    //格式化日期
    dateFilter(v) {
      let date = new Date(v);
      let year = date.getFullYear(); // 年
      let month = date.getMonth() + 1; // 月
      let day = date.getDate(); // 日
      var str = year + "-" + month + "-" + day;
      return str;
    },
    //选择座位
    selectSeat(index) {
      this.seatId = index + 1;
      let arr = Object.keys(this.seatList[index]);
      if (!this.seatList[index][arr[0]]) {
        this.getseatDue(); //预约
      } else {
        this.getseatUnDue(); //取消预约
      }
    },
    //某天某个时间段内所有座位的预约情况
    getseatstatus() {
      let that = this
      // const store = useStore();
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/getseatstatus/",
        type: "post",
        headers: {
          Authorization: "Bearer " + this.$store.state.user.token,
        },
        data: {
          selectedDateSlot: this.selectedDateSlot,
          selectedTimeSlot: this.timeSlots[this.selectedTimeSlot - 1].label,
        },
        success(resp) {
          console.log('某天某个时间段内所有座位的预约情况',resp);
          that.seatList = resp;
          console.log('jiekou fanhuifuzhi',that.seatList)
        },
        error: function (xhr, status, error) {
          console.error("发生错误:", error);
        },
      });
    },
    //预约接口
    getseatDue() {
      const that = this;
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/seatDue/",
        type: "post",
        headers: {
          Authorization: "Bearer " + this.$store.state.user.token,
        },
        data: {
          labelId: this.seatId,
          seatId: this.seatId,
          selectedDateSlot: this.selectedDateSlot,
          selectedTimeSlot: this.timeSlots[this.selectedTimeSlot - 1].label,
        },
        success(resp) {
          console.log(resp);
          that.showMessageFun(resp.message); //提示信息弹窗
          that.getseatstatus(); //重新获取座位
        },
      });
    },
    //取消预约
    getseatUnDue() {
      const that = this;
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/seatUnDue/",
        type: "delete",
        headers: {
          Authorization: "Bearer " + this.$store.state.user.token,
        },
        data: {
          seatId: this.seatId,
          selectedDateSlot: this.selectedDateSlot,
          selectedTimeSlot: this.timeSlots[this.selectedTimeSlot - 1].label,
        },
        success(resp) {
          console.log(resp);
          that.showMessageFun(resp.message); //提示信息弹窗
          that.getseatstatus(); //重新获取座位
        },
      });
    },
    /******************选择时间段设置***************************/
    selectTimeSlot(timeSlotId) {
      this.selectedTimeSlot = timeSlotId;
    },
    confirmTimeSlot() {
      if (this.selectedTimeSlot == null) {
        return;
      }
      this.step = 3;
      this.getseatstatus();
      // 如果用户没有选择时间段，不执行确认的操作
      // if (this.selectedTimeSlot !== null) {
      //   // 将选择的时间段记录在对应的座位按钮中
      //   const index = this.selectedSeat - 1;
      //   this.seatOptions[index].selectedTimeSlot = this.selectedTimeSlot;

      //   // 将selectedTimeSlot设置为选中时间段的label值
      //   this.selectedTimeSlot = this.timeSlots.find(
      //     (slot) => slot.id === this.selectedTimeSlot
      //   ).label;
      //   this.selectTSlot = this.selectedTimeSlot;
      //   // 调用 seatstatus 方法并将 seatId 和 selectedTimeSlot 传递给后端
      //   this.seatstatus(this.selectedSeat, this.selectedTimeSlot);

      //   this.closeTimeSlotModal();
      // }
      // // 刷新座位状态
      // this.getSeatId();
    },
    cancelTimeSlot() {
      if(this.seatList.length>0){
        this.step = 3
      }else{
        this.step = 4
      }
      this.closeTimeSlotModal();
    },
    resetChoose(){
      this.step=1;
      this.showTimeSlotModal=true;
      this.curselectedDateSlot=''
      this.selectedTimeSlot = ''
    },
    closeTimeSlotModal() {
      this.showTimeSlotModal = false;
      this.selectedSeat = null; // 清除选中座位
      this.selectedTimeSlot = null; // 清除选中时间段
    },
    /*****************************************************************/

    openModal() {
      this.showModal = true;
    },
    closeModal() {
      this.showModal = false;
      this.selectedSeat = null; // 清除选中座位
    },
  },
};
</script>

<style scoped>
.arrow-left-box{
  position: absolute;
  left: 24px;
  top: 30px;
  color: #4caf50;
}
.arrow-left{
  position: absolute;
  cursor: pointer;
}
.arrow-left:before,.arrow-left:after{
  position: absolute;
  content: '';
  border-top: 10px transparent dashed;
  border-left: 10px transparent dashed;
  border-bottom: 10px transparent dashed;
  border-right: 10px #ffffff solid;
}
.arrow-left:before{
  border-right: 10px #979797 solid;
}
.arrow-left:after{
  left: 2px; /*覆盖并错开1px*/
  border-right: 10px #ffffff solid;
}
.tips {
  position: fixed;
  top: 60px;
  left: 0;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.messagetext {
  display: inline-block;
  height: 40px;
  line-height: 40px;
  background: rgba(0, 0, 0, 0.6);
  padding: 0 60px;
  font-size: 18px;
  border-radius: 5px;
  color: #ffffff;
  box-shadow: 0px 0px 3px 2px rgba(0, 0, 0, 0.12);
}
.title {
  position: fixed;
  left: 50%;
  transform: translate(-50%, -50%);
  top: 20%;
}
.nextbtn {
  height: 40px;
  line-height: 40px;
  margin-top: 10px;
}
.seat-selector {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 50px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.seat-button {
  width: 50px;
  height: 50px;
  border: 1px solid #000;
  border-radius: 50%;
  margin: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.seat-button:hover {
  background-color: #ccc;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
  /* 确保模态框在其他元素之上 */
}

.modal-content {
  background-color: #ffffff;
  border-radius: 10px;
  padding: 20px;
  text-align: center;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
  /* 添加阴影效果 */
  max-width: 422px;
  /* 控制模态框的最大宽度 */
  width: 90%;
  /* 控制模态框的宽度 */
}

/* 关闭按钮样式 */
.close-button {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
  font-size: 18px;
  color: #777;
}

.close-button:hover {
  color: #333;
}

/* 新增样式用于选中座位的按钮 */
.selected-seat {
  background-color: red;
  color: white;
}

/*******************************/
/*时间段*/
.seat-buttons {
  display: flex;
  flex-wrap: wrap;
}
.curChoose {
  background: #4caf50 !important;
  color: #ffffff;
}
.dateitem button:hover {
  cursor: pointer;
  background: #4caf50;
  color: #ffffff;
}
.btnbox {
  display: flex;
  justify-content: space-between;
  height: 38px;
  line-height: 36px;
  margin-top: 10px;
  overflow: hidden;
}
.btnbox button {
  width: 40%;
  color: #000;
  border: 1px solid #000;
}
.time-slot-button {
  margin: 5px;
  padding: 10px;
  cursor: pointer;
  border: 1px solid #ccc;
}

.selected-time-slot {
  background-color: #4caf50;
  color: white;
}

.time-slot-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}
/* 可根据需要自定义模态框的样式 */
</style>
